// lib/base/error.ts

// 基础错误类
export class BaseError extends Error {
  constructor(message: string, public code?: string, public data?: unknown) {
    super(message);
    this.name = this.constructor.name;
  }
}

// HTTP错误
export class HttpError extends BaseError {
  constructor(public status: number, message: string, data?: unknown) {
    super(message, `HTTP_${status}`, data);
  }

  static isHttpError(error: unknown): error is HttpError {
    return error instanceof HttpError;
  }
}

// 认证错误
export class AuthError extends BaseError {
  constructor(message: string, code = "AUTH_ERROR") {
    super(message, code);
  }

  static isAuthError(error: unknown): error is AuthError {
    return error instanceof AuthError;
  }
}

// 业务错误
export class BusinessError extends BaseError {
  constructor(message: string, code: string) {
    super(message, code);
  }

  static isBusinessError(error: unknown): error is BusinessError {
    return error instanceof BusinessError;
  }
}

// 验证错误
export class ValidationError extends BaseError {
  constructor(message: string, public fields?: Record<string, string[]>) {
    super(message, "VALIDATION_ERROR", fields);
  }

  static isValidationError(error: unknown): error is ValidationError {
    return error instanceof ValidationError;
  }
}

// 网络错误
export class NetworkError extends BaseError {
  constructor(message = "网络连接失败") {
    super(message, "NETWORK_ERROR");
  }

  static isNetworkError(error: unknown): error is NetworkError {
    return error instanceof NetworkError;
  }
}

// 超时错误
export class TimeoutError extends BaseError {
  constructor(message = "请求超时") {
    super(message, "TIMEOUT_ERROR");
  }

  static isTimeoutError(error: unknown): error is TimeoutError {
    return error instanceof TimeoutError;
  }
}

// 错误工具函数
export const isAppError = (error: unknown): error is BaseError => {
  return error instanceof BaseError;
};

// 错误码定义
export const ErrorCodes = {
  // HTTP 错误
  HTTP_400: "BAD_REQUEST",
  HTTP_401: "UNAUTHORIZED",
  HTTP_403: "FORBIDDEN",
  HTTP_404: "NOT_FOUND",
  HTTP_500: "INTERNAL_SERVER_ERROR",

  // 认证错误
  AUTH_INVALID_CREDENTIALS: "INVALID_CREDENTIALS",
  AUTH_TOKEN_EXPIRED: "TOKEN_EXPIRED",
  AUTH_TOKEN_INVALID: "TOKEN_INVALID",
  AUTH_USER_NOT_FOUND: "USER_NOT_FOUND",

  // 业务错误
  BUSINESS_INVALID_OPERATION: "INVALID_OPERATION",
  BUSINESS_RESOURCE_NOT_FOUND: "RESOURCE_NOT_FOUND",
  BUSINESS_DUPLICATE_ENTRY: "DUPLICATE_ENTRY",

  // 验证错误
  VALIDATION_REQUIRED: "FIELD_REQUIRED",
  VALIDATION_INVALID_FORMAT: "INVALID_FORMAT",
  VALIDATION_TOO_SHORT: "TOO_SHORT",
  VALIDATION_TOO_LONG: "TOO_LONG",
} as const;
